package co.yixiang.yshop.module.product.controller.admin.storeproduct;

import co.yixiang.yshop.framework.common.enums.CommonStatusEnum;
import co.yixiang.yshop.framework.common.pojo.CommonResult;
import co.yixiang.yshop.framework.common.pojo.PageResult;
import co.yixiang.yshop.framework.excel.core.util.ExcelUtils;
import co.yixiang.yshop.framework.operatelog.core.annotations.OperateLog;
import co.yixiang.yshop.module.product.controller.admin.storeproduct.vo.*;
import co.yixiang.yshop.module.product.convert.storeproduct.StoreProductConvert;
import co.yixiang.yshop.module.product.dal.dataobject.storeproduct.StoreProductDO;
import co.yixiang.yshop.module.product.service.storeproduct.StoreProductService;
import co.yixiang.yshop.module.product.service.storeproduct.dto.StoreProductDTO;
import co.yixiang.yshop.module.system.enums.common.SexEnum;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.annotation.security.PermitAll;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

import static co.yixiang.yshop.framework.common.pojo.CommonResult.success;
import static co.yixiang.yshop.framework.operatelog.core.enums.OperateTypeEnum.EXPORT;

@Tag(name = "管理后台 - 商品")
@RestController
@RequestMapping("/product/store-product")
@Validated
public class StoreProductController {

    @Resource
    private StoreProductService storeProductService;


    @PostMapping("/create")
    @Operation(summary = "创建商品")
    @PreAuthorize("@ss.hasPermission('shop:store-product:create')")
    public CommonResult<Boolean> createStoreProduct(@Valid @RequestBody StoreProductDTO storeProductDto) {
        storeProductService.insertAndEditYxStoreProduct(storeProductDto);
        return success(true);
    }

    @PostMapping("/addStock")
    @Operation(summary = "补充库存")
    public CommonResult<Boolean> addStock(@Valid @RequestBody StoreProductDTO storeProductDto) {
        storeProductService.addStock(storeProductDto);
        return success(true);
    }

    @PutMapping("/update")
    @Operation(summary = "更新商品")
    @PreAuthorize("@ss.hasPermission('shop:store-product:update')")
    public CommonResult<Boolean> updateStoreProduct(@Valid @RequestBody StoreProductUpdateReqVO updateReqVO) {
        storeProductService.updateStoreProduct(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除商品")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('shop:store-product:delete')")
    public CommonResult<Boolean> deleteStoreProduct(@RequestParam("id") Long id) {
        storeProductService.deleteStoreProduct(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得商品")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('shop:store-product:query')")
    public CommonResult<StoreProductRespVO> getStoreProduct(@RequestParam("id") Long id) {
        StoreProductRespVO vo = storeProductService.getStoreProductDetails(id);
        return success(vo);
    }

    @GetMapping("/list")
    @Operation(summary = "获得商品列表")
    @Parameter(name = "ids", description = "编号列表", required = true, example = "1024,2048")
    @PreAuthorize("@ss.hasPermission('shop:store-product:query')")
    public CommonResult<List<StoreProductRespVO>> getStoreProductList(@RequestParam("ids") Collection<Long> ids) {
        List<StoreProductDO> list = storeProductService.getStoreProductList(ids);
        return success(StoreProductConvert.INSTANCE.convertList(list));
    }

    @GetMapping("/page")
    @Operation(summary = "获得商品分页")
    @PreAuthorize("@ss.hasPermission('shop:store-product:query')")
    public CommonResult<PageResult<StoreProductRespVO>> getStoreProductPage(@Valid StoreProductPageReqVO pageVO) {
        PageResult<StoreProductDO> pageResult = storeProductService.getStoreProductPage(pageVO);
        return success(StoreProductConvert.INSTANCE.convertPage(pageResult));
    }

    @PostMapping("/coupon/page")
    @Operation(summary = "获得优惠券商品分页")
    public CommonResult<PageResult<StoreProductRespVO>> getCouponProductPage(@Valid @RequestBody CouponProductPageReqVO pageVO) {
        PageResult<StoreProductDO> pageResult = storeProductService.getCouponProductPage(pageVO);
        return success(StoreProductConvert.INSTANCE.convertPage(pageResult));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出商品 Excel")
    @PreAuthorize("@ss.hasPermission('shop:store-product:export')")
    @OperateLog(type = EXPORT)
    public void exportStoreProductExcel(@Valid StoreProductExportReqVO exportReqVO,
                                        HttpServletResponse response) throws IOException {
        List<StoreProductDO> list = storeProductService.getStoreProductList(exportReqVO);
        // 导出 Excel
        List<StoreProductExcelVO> datas = StoreProductConvert.INSTANCE.convertList02(list);
        ExcelUtils.write(response, "商品.xls", "数据", StoreProductExcelVO.class, datas);
    }

    @Operation(summary = "获取商品信息")
    @GetMapping(value = "/info/{id}")
    public CommonResult<Map<String, Object>> info(@PathVariable Long id) {
        return success(storeProductService.getProductInfo(id));
    }


    @Operation(summary = "生成属性")
    @PostMapping(value = "/isFormatAttr/{id}")
    public CommonResult<Map<String, Object>> isFormatAttr(@PathVariable Long id, @RequestBody String jsonStr) {
        return success(storeProductService.getFormatAttr(id, jsonStr, false));
    }

    @Operation(summary = "生成库存属性")
    @PostMapping(value = "/isSkuFormatAttr/{id}")
    public CommonResult<Map<String, Object>> isSkuFormatAttr(@PathVariable Long id, @RequestBody String jsonStr) {
        return success(storeProductService.getStockFormatAttr(id, jsonStr));
    }

    @Operation(summary = "商品上架/下架")
    @GetMapping(value = "/sale")
    public CommonResult<Boolean> onSale(@RequestParam("id") Long id, @RequestParam("type") int status) {
        storeProductService.onSale(id, status);
        return success(true);
    }

    @GetMapping("/campaign-product/page")
    @Operation(summary = "获得营销活动商品列表")
    public CommonResult<PageResult<CampaignProductRespVO>> getCampaignProductPage(@Valid CampaignProductPageReqVO pageVO) {
        return success(storeProductService.getCampaignProductPage(pageVO));
    }

    @GetMapping("/canvas/page")
    @Operation(summary = "获得画布商品分页")
    @PreAuthorize("@ss.hasPermission('shop:store-product:canvas:query')")
    public CommonResult<PageResult<StoreProductRespVO>> getCanvasProductPage(@Valid CanvasProductPageReqVO pageVO) {
        return success(storeProductService.getCanvasProductPage(pageVO));
    }

    @PostMapping("import")
    @Operation(summary = "导入商品")
    @PreAuthorize("@ss.hasPermission('shop:store-product:create')")
    @PermitAll
    public CommonResult<String> importProduct(@RequestParam("file") MultipartFile file) throws Exception {
        // 检查文件是否为空
        if (file.isEmpty()) {
            throw new IllegalArgumentException("上传的文件不能为空");
        }

        // 检查文件大小
        if (file.getSize() == 0) {
            throw new IllegalArgumentException("上传的文件大小为零");
        }

        storeProductService.importProduct(file);
        return success("导入成功");
  }


    @GetMapping("/download-template")
    @Operation(summary = "下载导入商品模版")
    public void downloadTemplate(HttpServletResponse response) throws IOException {
        // 导出 Excel
        List<StoreProductImportVO> list = Arrays.asList(
                StoreProductImportVO.builder().storeName("商品名称").cateName("这里填分类名称").keyword("关键字").image("在线完整图片链接")
                        .isShowStr("上架").storeInfo("商品简介").price(new BigDecimal("10"))
                        .cost(new BigDecimal("10"))
                        .otPrice(new BigDecimal("10"))
                        .stock(99)
                        .barCode("00001")
                        .volume(new BigDecimal("0.1"))
                        .weight(new BigDecimal("0.2"))
                        .build()
        );
        ExcelUtils.write(response, "商品导入模版.xls", "模版", StoreProductImportVO.class, list);
    }

}
